import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';


const BOARD_SIZE = 3;
const LINE_SIZE = 3;

function Square(props) {
    return(
        <button
            className="square"
            onClick={props.onClick}>
            {props.value}
        </button>
    );
}


class Board extends React.Component {


    renderSquare(x,y) {
        return <Square value={this.props.chessBoard[x][y]} onClick={() => this.props.onClick(x,y)}/>;
    }

    getRow(rowNo) {
        let row = [];
        for (let i = 0; i < this.props.boardSize; i++) {
            row.push(this.renderSquare(rowNo,i))
        }
        return row;
    }

    render(){
        let square  = [];
        for (let i = 0; i < this.props.boardSize; i++) {
            square.push(<div className="board-row">{this.getRow(i)}</div>)
        }
       
        return (
            <div>
                {square}
            </div>
        );
    }
}

class Game extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            chessBoard : this.getChessBoard(),
            history : [],
            xIsNext : true,
            stepNumber: 0,
            win : false
        }
    }

    getChessBoard(){
        let chessBoard = [];
        for (let i = 0; i < this.props.boardSize; i++) {
            chessBoard[i] = Array(this.props.boardSize);
        }
        return chessBoard;
    }

    handleClick(x, y) {
        const chessBoard = this.state.chessBoard.concat([]);
        const beHistory = deepCopy(chessBoard);
        // const beHistory = chessBoard.slice();
        let history = this.state.history.slice(0, this.state.stepNumber);
        history.push(beHistory);
        let step = history.length;
        if (chessBoard[x][y] != null || this.state.win){
            return
        }
        let chessType = this.state.xIsNext ? 'X' : 'O';
        const win = this.calculateWinner(x, y);
        chessBoard[x][y] = chessType;
        this.setState({
            chessBoard : chessBoard,
            history : history,
            xIsNext : !this.state.xIsNext,
            chessType : chessType,
            stepNumber : step,
            win : win
        });
    }

    calculateWinner(x, y) {
        const directions = [{x: 1, y: 1},{x: 1, y: -1},{x: 1, y: 0},{x: 0, y: 1}]
        for (let direction of directions){
            let hasWinner = this.chessOnLine(x, y, direction.x, direction.y,)
            if(hasWinner){
                return true;
            }
        }
        return false;

    }

    chessOnLine(x, y, offsetX, offsetY){
        const chessType = this.state.xIsNext ? 'X' : 'O';
        let
            count = 1,
            direction = 1,
            nextX = x,
            nextY = y,
            bound = this.props.boardSize,
            nearChessType;
        getNextChess(this);
        return count >= this.props.lineSize;

        function getNextChess(that){
            nextX += offsetX*direction;
            nextY += offsetY*direction;
            let xOutBound = (nextX < 0 || nextX >= bound);
            let yOutBound = (nextY < 0 || nextY >= bound);
            if (xOutBound || yOutBound){
                if (direction === -1){
                    return ;
                }
                nextX = x;
                nextY = y;
                direction = -1;
                getNextChess(that);
            }else {
                nearChessType = that.state.chessBoard[nextX][nextY]
                if (chessType === nearChessType){
                    count++;
                    getNextChess(that);
                }else if (direction === 1){
                    direction = -1;
                    nextX = x;
                    nextY = y;
                    getNextChess(that);
                }
            }
        }
    }

    jumpTo(step) {
        this.setState({
            chessBoard : this.state.history[step],
            stepNumber: step,
            xIsNext: (step % 2) === 0,
        });
    }

    render() {
        const moves = this.state.history.map((chessBoard, index) => {
            const desc = index ?
                'Go to move #' + index :
                'Go to game start';
            return (
                <li key={index}>
                    <button onClick={() => this.jumpTo(index)}>{desc}</button>
                </li>
            );
        });

        const winner = this.state.win;
        let status;
        if (winner) {
            status = 'Winner: ' + this.state.chessType;
        } else {
            status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
        }

        return (
            <div>
                <div className="game">
                    <div className="game-board">
                        <Board chessBoard={this.state.chessBoard} boardSize={this.props.boardSize} lineSize={3} onClick={(x,y) => this.handleClick(x,y)}/>
                    </div>
                    <div className="game-info">
                        <div>{status}</div>
                        <ol>{moves}</ol>
                    </div>
                </div>
            </div>
        );
    }
}

function deepCopy(array) {
    const berry = []
    for (let item of array){
        if (item instanceof Array){
            berry.push(deepCopy(item));
        }else {
            berry.push(item);
        }

    }
    return berry
}

// ========================================

ReactDOM.render(
    <Game boardSize={15} lineSize={5}/>,
    // <Chess />,
    document.getElementById('root')
);
